package com.foxmail.yusp.mycloud;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Switch;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

import static android.support.v7.widget.DividerItemDecoration.VERTICAL;

public class RelayActivity extends AppCompatActivity {

    @BindView(R.id.r_0)
    RadioButton r_0;
    @BindView(R.id.r_1)
    RadioButton r_1;
    @BindView(R.id.r_2)
    RadioButton r_2;

    @BindView(R.id.et_title)
    EditText et_title;
    @BindView(R.id.s1)
    Switch s_enable;

    @BindView(R.id.continuous)
    RadioButton is_continuous;

    @BindView(R.id.et_on)
    EditText et_on;
    @BindView(R.id.et_off)
    EditText et_off;

    @BindView(R.id.schedules)
    RecyclerView rvSchedules;

    private ArrayList<Schedule> schedules = new ArrayList<>();
    private Relay r0, r1, r2;
    private MyMQTT myMQTT;
    private ScheduleAdapter adapter;
    private String r = "r0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_relay);
        // bind
        ButterKnife.bind(this);
        // lists
        adapter = new ScheduleAdapter(this, schedules);
        rvSchedules.setAdapter(adapter);
        rvSchedules.setLayoutManager(new LinearLayoutManager(this));
        DividerItemDecoration decoration = new DividerItemDecoration(this, VERTICAL);
        rvSchedules.addItemDecoration(decoration);
        //mqtt
        myMQTT = new MyMQTT(getApplicationContext(), "/th/#",
                "tcp://m13.cloudmqtt.com:18957", "yusp", "60240abc");
        myMQTT.setStateListener(new MyMQTT.StateListener() {
            @Override
            public void stateListner(String state) {
                if (state.equals("连接成功")) {
                    myMQTT.get_key("r0");
                }
            }
        });

        myMQTT.setMsgListener(new MyMQTT.MsgListener() {
            @Override
            public void msgListner(JSONObject obj) {
                relay_info(obj);
            }
        });

        myMQTT.connect();
    }

    private void relay_info(JSONObject obj) {
        //当前继电器
        try {
            JSONObject obj_2 = obj.getJSONObject("result");
            Relay r = new Relay(obj_2.getInt("idx"),
                    obj_2.getBoolean("enable"),
                    obj_2.getBoolean("pulse"),
                    obj_2.getInt("on"),
                    obj_2.getInt("off"),
                    obj_2.getString("title"),
                    obj_2.getInt("priority"),
                    obj_2.getString("schedule")
            );
            if (obj.getString("tag").equals("r0")) {
                r0 = r;
            } else if (obj.getString("tag").equals("r1")) {
                r1 = r;
            } else if (obj.getString("tag").equals("r2")) {
                r2 = r;
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        //
        display_relay_info(r0);
    }

    //显示Relay继电器信息
    private void display_relay_info(Relay r) {
        et_title.setText(r.getTitle());
        et_on.setText(r.getOn());
        et_off.setText(r.getOff());

        try {
            JSONObject obj = new JSONObject(r.getSchedule());
            schedules.clear();
            schedules.add(new Schedule(1, obj.getInt("a0"), obj.getInt("a1")));
            schedules.add(new Schedule(2, obj.getInt("b0"), obj.getInt("b1")));
            schedules.add(new Schedule(3, obj.getInt("c0"), obj.getInt("c1")));
            schedules.add(new Schedule(4, obj.getInt("d0"), obj.getInt("d1")));
            schedules.add(new Schedule(5, obj.getInt("e0"), obj.getInt("e1")));
            schedules.add(new Schedule(6, obj.getInt("f0"), obj.getInt("f1")));
            adapter.notifyDataSetChanged();

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //继电器选择
    @OnCheckedChanged({R.id.r_0, R.id.r_1, R.id.r_2})
    public void rg_relay_change(CompoundButton button, boolean checked) {
        switch (button.getId()) {
            case R.id.r_0:
                myMQTT.get_key("r0");
                r = "r0";
                break;

            case R.id.r_1:
                myMQTT.get_key("r1");
                r = "r1";
                break;

            case R.id.r_2:
                myMQTT.get_key("r2");
                r = "r2";
                break;
        }
    }

    // 保存
    @OnClick(R.id.btnSave)
    public void btnSave(View view) {
        RelayFrame.Schedule schedule = new RelayFrame.Schedule(
                Integer.parseInt(schedules.get(0).getStart()), Integer.parseInt(schedules.get(0).getOn_time()),
                Integer.parseInt(schedules.get(1).getStart()), Integer.parseInt(schedules.get(1).getOn_time()),
                Integer.parseInt(schedules.get(2).getStart()), Integer.parseInt(schedules.get(2).getOn_time()),
                Integer.parseInt(schedules.get(3).getStart()), Integer.parseInt(schedules.get(3).getOn_time()),
                Integer.parseInt(schedules.get(4).getStart()), Integer.parseInt(schedules.get(4).getOn_time()),
                Integer.parseInt(schedules.get(5).getStart()), Integer.parseInt(schedules.get(5).getOn_time())
        );
        Gson gson = new Gson();
        String json = gson.toJson(new RelayFrame(new RelayFrame.Config(new RelayFrame.R0(
                s_enable.isChecked(),
                et_title.getText().toString(),
                is_continuous.isChecked(),
                Integer.parseInt(et_on.getText().toString()),
                Integer.parseInt(et_off.getText().toString()),
                schedule
        ))));
        json = json.replace("r0", r);
        myMQTT.put_key(json, "set_relay_" + r);
    }

    //end
}
